package com.quotes.ui;

import java.awt.BorderLayout;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.EventListenerList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.log4j.Logger;
import com.quotes.datamodell.DataChangedEventListener;
import com.quotes.datamodell.DataRepository;
import com.quotes.datamodell.Quotes;
import com.quotes.datamodell.QuotesList;

public class QuotesListPanel extends JPanel implements DataChangedEventListener, ListSelectionListener
{
	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(getClass().toString());
	private EventListenerList listenerList = new EventListenerList();
	private DataRepository repository = null;
	private JList<Quotes> list = null;
	private DefaultListModel<Quotes> listModel = null; 
	
	public QuotesListPanel(DataRepository repository) {
		this.repository = repository;
		this.repository.addDataChangedEventListener(this);
		this.setLayout(new BorderLayout());
		
		listModel = new DefaultListModel<Quotes>();
		list = new JList<Quotes>(listModel);
		list.addListSelectionListener(this);
		JScrollPane scrollPane = new JScrollPane(list);
		scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		this.add(scrollPane, BorderLayout.CENTER);
		
		reloadSymbolNamesIntoList();
		logger.debug("QuotesListPanel created!");
	}
	
	public void addQuotesListSelectionChangedEvent(QuotesListSelectionChangedListener listener) {
        listenerList.add(QuotesListSelectionChangedListener.class, listener);
    }
    
    public void removeQuotesListSelectionChangedEvent(QuotesListSelectionChangedListener listener) {
        listenerList.remove(QuotesListSelectionChangedListener.class, listener);
    }
    
    private void fireQuotesListSelectionChangedEvent(QuotesList list) {
        Object[] listeners = listenerList.getListenerList();

        for (int i=0; i<listeners.length; i+=2) {
            if (listeners[i] == QuotesListSelectionChangedListener.class) {
                ((QuotesListSelectionChangedListener)listeners[i+1]).selectionChanged(list);
            }
        }
    }
	
	public void reloadSymbolNamesIntoList() {
		if (repository.isDataLoaded()) {
			listModel = new DefaultListModel<Quotes>();
			
			for (Quotes quotes : repository.getQuotesList().getQuotes()) {
				listModel.addElement(quotes);
			}
			
			list.setModel(listModel);
			revalidate();
		}
	}

	@Override
	public void dataChanged(DataRepository repository) {
		logger.debug("Received dataChanged event from DataRepository!");
		reloadSymbolNamesIntoList();
	}

	@Override
	public void valueChanged(ListSelectionEvent event) {
		QuotesList quotes = new QuotesList();
		
		for (Quotes q : list.getSelectedValuesList()) {
			quotes.add(q);
		}
		
		this.fireQuotesListSelectionChangedEvent(quotes);
	}
}
